package com.westar.base.businessUtil;

import com.westar.base.util.JsoupSelfUtil;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class NextTaskInfoUtil {

    /**
     * 审核办件
     * @param actCookie
     * @param nextNodeInfoPage 下一步骤配置界面
     * @param parentPage 办件信息详情页面
     * @param fisrtHandleAccount 办件受理人员
     * @throws Exception
     */
    public static void jiexiPage(String actCookie,String nextNodeInfoPage, String parentPage,String fisrtHandleAccount) throws Exception {
        Document doc = Jsoup.parse(nextNodeInfoPage);
        Elements scripts = doc.select("script");

        Map<String,String> pageParam = new HashMap<>();
        for(Element script : scripts){
            if(script.html().contains("var busiAlias_ =")) { //注意这里一定是html(), 而不是text()
                Map<String,String> searchParam = NextTaskInfoUtil.getSearchParamForTaskInfo(script.html());
                //自己不是受理人员
                if(StringUtils.isNotEmpty(fisrtHandleAccount)){
                    searchParam.put("myselfLoginId",fisrtHandleAccount);
                }
                String busiAlias = searchParam.get("busiAlias");
                if(StringUtils.isNotEmpty(busiAlias) && busiAlias.equals("COMMON-MODEL")){
                    String  myselfLoginId = searchParam.get("myselfLoginId");
                    //指定下一步办理人
                    Map<String,String> map = NextTaskInfoUtil.relyApplyCaseSubmit(actCookie,nextNodeInfoPage,myselfLoginId);
                    Document docP = Jsoup.parse(parentPage);
                    if(null != map && !map.isEmpty() ){
                        Iterator<Map.Entry<String,String>> itor = map.entrySet().iterator();
                        while (itor.hasNext()){
                            Map.Entry<String,String> entry = itor.next();
                            String key = entry.getKey();
                            String value = entry.getValue();

                            docP.select( "#"+key ).attr( "value",value );
                        }
                    }
                    parentPage = docP.outerHtml();

                    String submitType = searchParam.get("submitType");
                    if(submitType.equals( "7" )){
                        ViewTaskUtil.submitTask(actCookie, "7",parentPage );
                    }else if(submitType.equals( "1" )){
                        ViewTaskUtil.accept(actCookie,parentPage);
                    }else if(submitType.equals( "3" )){
                        ViewTaskUtil.make(actCookie,parentPage,"3");
                    }else if(submitType.equals( "8" )){
                        //是否在当前环节打印办结通知书?
//                        ViewTaskUtil.submitTaskForNotice(token,parentPage,"8");
                        ViewTaskUtil.submitTask(actCookie, "8",parentPage );
                    }else if(submitType.equals( "11" )){
                        ViewTaskUtil.submitTask(actCookie, "11",parentPage );
                    }else if(submitType.equals( "9" )){
                        LicenseUtil.makeDone(actCookie,parentPage);
                    }else if(submitType.equals( "10" )){
                        ViewTaskUtil.submitTask(actCookie, "10",parentPage );
                    }

                }else{
                    Map<String, String> postParam = NextTaskInfoUtil.returnParams4App(searchParam,nextNodeInfoPage);
                    boolean state = WorkflowUtil.completeTask(actCookie,postParam);
                }
                break;

            }
        }

    }

    /**
     *
     * @param searchParam
     * @param pageInfo
     */
    private static Map<String, String> returnParams4App(Map<String, String> searchParam, String pageInfo) {

        Document doc = Jsoup.parse(pageInfo);
        Elements eleForm = doc.select("body");

        String isMutilTask = searchParam.get( "isMutilTask" );
        Map<String, String> postParam = new HashMap<>( );
        if(StringUtils.isNotEmpty( isMutilTask ) &&  isMutilTask.equals( "true" )){
            String shardKey = eleForm.select( "#shardKey" ).attr( "value" );
            String procTaskId = eleForm.select( "#taskId" ).attr( "value" );
            postParam.put("shardKey",shardKey );
            postParam.put("procTaskId",procTaskId );
        }else{
            String nextNodeId = null;
            Elements elements = eleForm.select( "input[name=\"nextNodeRadio\"]" );
            //默认单选框的值为空
            String radioVal = "";
            //便利单选选项
            for (Element radio :elements){
                //单选框被选中
                if(radio.hasAttr( "checked" )){
                    //获取数据
                    nextNodeId = radio.attr( "value" );
                    //终止循环
                    break;
                }
            }

            String curEl = NextTaskInfoUtil.getELString(eleForm);

            Map<String,String> appointUserIdAndGrpMap = NextTaskInfoUtil.getAppointUserIdAndGrpMap(eleForm);

//        String  appUserId = eleForm.select("#appointUserId").attr( "value" );
            String  appUserId = appointUserIdAndGrpMap.getOrDefault("appointUserId","");


//            String appUserId =  eleForm.select( "#appointUserId" ).attr( "value" );
            //添加办件的办理人员
            appUserId = addMyself(appUserId,searchParam);

            String caseName = eleForm.select( "#caseName" ).attr( "value" );
            String shardKey = eleForm.select( "#shardKey" ).attr( "value" );
            String procTaskId = eleForm.select( "#taskId" ).attr( "value" );
            String appointUserId = appUserId;

            String appointGroupIdDef = eleForm.select("#appointGroupId").attr( "value" );
            String appointGroupId = appointUserIdAndGrpMap.getOrDefault("appointGroupId",appointGroupIdDef);

            postParam.put("caseName",caseName );
            postParam.put("shardKey",shardKey );
            postParam.put("procTaskId",procTaskId );
            postParam.put("appointUserId",appointUserId );
            postParam.put("appointGroupId",appointGroupId );
            postParam.put("nextNodeId",nextNodeId );

            if(StringUtils.isNotEmpty( curEl )){
                String[] arr = curEl.split( "==" );
                if(arr.length == 2){
                    postParam.put(arr[0],arr[1] );
                }

            }
        }
        return postParam;

    }

    /**
     * 添加自己为办理人
     * @param manyUsers
     * @param searchParam
     * @return
     */
    private static String addMyself(String manyUsers, Map<String, String> searchParam) {
        String myselfLoginId = searchParam.get( "myselfLoginId" );
        if(StringUtils.isEmpty( manyUsers )){
            return myselfLoginId;
        }else{
            //添加当前办理人员
            String[] appointUserIds = manyUsers.split(",");
            List<String> appointUserIdList = new ArrayList<>();
            for (int i=0,len = appointUserIds.length;i<len ;i++){
                if(i<10){
                    appointUserIdList.add(appointUserIds[i]);
                }
            }
            //添加自己为办理人
            if(StringUtils.isNotEmpty(myselfLoginId ) && !appointUserIdList.contains(myselfLoginId)){
                appointUserIdList.add(0,myselfLoginId);
            }

            String resU = "";
            for (int i = 0,len = appointUserIdList.size();i < len ;i++){
                if(i<10){
                    resU += ","+appointUserIdList.get(i);
                }
            }
            resU = resU.substring(1,resU.length());
            return resU;
        }
    }

    /**
     * 指定下一步骤的办理人员
     * @param actCookie
     * @param pageInfo
     * @return
     */
    private static  Map<String,String> relyApplyCaseSubmit(String actCookie, String pageInfo,String myselfLoginId) {
        Document doc = Jsoup.parse(pageInfo);
        Elements eleForm = doc.select("body");

        String curEl = NextTaskInfoUtil.getELString(eleForm);
        Map<String,String> appointUserIdAndGrpMap = NextTaskInfoUtil.getAppointUserIdAndGrpMap(eleForm);

//        String  appointUserId = eleForm.select("#appointUserId").attr( "value" );
        String  appointUserId = appointUserIdAndGrpMap.getOrDefault("appointUserId","");
        String appointGroupIdDef = eleForm.select("#appointGroupId").attr( "value" );
        String appointGroupId = appointUserIdAndGrpMap.getOrDefault("appointGroupId",appointGroupIdDef);
        //添加当前办理人员
        if(StringUtils.isNotEmpty(myselfLoginId)){
            List<String> appointUserIdList = new ArrayList<>();
            if(StringUtils.isEmpty(appointUserId)){
                appointUserIdList.add(0,myselfLoginId);
            }else{
                String[] appointUserIds = appointUserId.split(",");
                for (int i=0,len = appointUserIds.length;i<len ;i++){
                    if(i<10){
                        appointUserIdList.add(appointUserIds[i]);
                    }
                }
                if(!appointUserIdList.contains(myselfLoginId)){
                    appointUserIdList.add(0,myselfLoginId);
                }
            }

            String resU = "";

            for (int i = 0,len = appointUserIdList.size();i < len ;i++){
                if(i<10){
                    resU += ","+appointUserIdList.get(i);
                }
            }
            resU = resU.substring(1,resU.length());
            appointUserId = resU;
        }

        Map<String,String> forParentMap = new HashMap<>(  );
        forParentMap.put("elCondition_", curEl );
        forParentMap.put("applyUsersLoginId_", appointUserId );
        forParentMap.put("applyUsersDeptCode_", appointGroupId );

        String nextNodeId = appointUserIdAndGrpMap.get("nextNodeId");
        forParentMap.put("nextNodeId_",nextNodeId );

        String nextHandlerJSON = eleForm.select("input#userlist_"+nextNodeId).attr("value");
        forParentMap.put("nextHandlerJSON_", nextHandlerJSON );

        return forParentMap;
    }

    private static Map<String, String> getAppointUserIdAndGrpMap(Elements eleForm) {
        Map<String, String> map = new HashMap<>();
        String selectedNodeId = null;
        try {
            Elements elements = eleForm.select( "input[name=\"nextNodeRadio\"]" );
            //默认单选框的值为空
            String radioVal = "";
            //便利单选选项
            for (Element radio :elements){
                //单选框被选中
                if(radio.hasAttr( "checked" )){
                    //获取数据
                    selectedNodeId = radio.attr( "value" );
                    //终止循环
                    break;
                }
            }
        }catch (Exception e){
            selectedNodeId = eleForm.select( "#branch" ).select( "option" ).get(0).attr("value");
        }
        String curLoginId_ = eleForm.select("#loginId_"+selectedNodeId).attr("value");
        String curdeptCode_ = eleForm.select("#deptCode_"+selectedNodeId).attr("value");
        Elements trs = eleForm.select("tr[title='"+selectedNodeId+"']");
        if(!trs.isEmpty() && trs.size() == 1){
            map.put("appointUserId",curLoginId_);
            map.put("appointGroupId",curdeptCode_);
            map.put("nextNodeId",selectedNodeId);
        }
        return map;

    }

    private static String getELString(Elements eleForm) {
        String elString = null;
        try {
            Elements elements = eleForm.select( "input[name=\"nextNodeRadio\"]" );
            //默认单选框的值为空
            String radioVal = "";
            //便利单选选项
            for (Element radio :elements){
                //单选框被选中
                if(radio.hasAttr( "checked" )){
                    //获取数据
                    elString = radio.attr( "elCondition" );
                    //终止循环
                    break;
                }
            }
        }catch (Exception e){
            elString = eleForm.select( "#branch" ).select( "option" ).get(0).attr("elCondition");
        }

        if(StringUtils.isNotEmpty(elString)){
            elString = elString.replaceAll( "/[ ]/g","" );
            return elString;
        }else{
            return  "null";
        }

    }

    private static Map<String, String> getSearchParamForTaskInfo(String html) {

        Map<String, String> result = new HashMap<>();
        String str = html.replace("\r\n", ""); //这里是为了解决 无法多行匹配的问题

        //获得参数taskId
        String regixBusiAlias = "var busiAlias_ =\\ (.*?);"; //()必须加，
        Pattern patternBusiAlias = Pattern.compile(regixBusiAlias,Pattern.MULTILINE);
        Matcher matcherBusiAlias = patternBusiAlias.matcher(str);
        if(matcherBusiAlias.find()){
            String option_1 = matcherBusiAlias.group();
            String busiAlias = option_1.replace( "var busiAlias_ =","" )
                    .replaceAll( ";","" )
                    .replaceAll( "\'","" )
                    .trim();

            result.put( "busiAlias",busiAlias );
        }

        //获得参数busiId
        String regixSubmitType = "var submitType_ =\\ (.*?);"; //()必须加，
        Pattern patternSubmitType = Pattern.compile(regixSubmitType,Pattern.MULTILINE);
        Matcher matcherSubmitType = patternSubmitType.matcher(str);
        if(matcherSubmitType.find()){
            String option_1 = matcherSubmitType.group();
            String submitType = option_1.replace( "var submitType_ =","" )
                    .replaceAll( ";","" )
                    .replaceAll( "\'","" )
                    .trim();
            result.put( "submitType",submitType );
        }
        //获得参数busiId
        String regixIsMutilTask = "var isMutilTask=(.*?);"; //()必须加，
        Pattern patternIsMutilTask = Pattern.compile(regixIsMutilTask,Pattern.MULTILINE);
        Matcher matcherIsMutilTask = patternIsMutilTask.matcher(str);
        if(matcherIsMutilTask.find()){
            String option_1 = matcherIsMutilTask.group();
            String isMutilTask = option_1.replace( "var isMutilTask=","" )
                    .replaceAll( ";","" )
                    .replaceAll( "\'","" )
                    .trim();
            result.put( "isMutilTask",isMutilTask );
        }
        //获得参数busiId
        String regixMyselfLoginId = "var myselfLoginId =\\ (.*?);"; //()必须加，
        Pattern patternMyselfLoginId = Pattern.compile(regixMyselfLoginId,Pattern.MULTILINE);
        Matcher matcherMyselfLoginId = patternMyselfLoginId.matcher(str);
        if(matcherMyselfLoginId.find()){
            String option_1 = matcherMyselfLoginId.group();
            String myselfLoginId = option_1.replace( "var myselfLoginId = ","" )
                    .replaceAll( ";","" )
                    .replaceAll( "\'","" )
                    .trim();
            result.put( "myselfLoginId",myselfLoginId);
        }
        return result;
    }
}
